package org.mzyyn.qr.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.mzyyn.qr.constants.RedisKeyConstant;
import org.mzyyn.qr.constants.ShareConstant;
import org.mzyyn.qr.context.UserAuthContext;
import org.mzyyn.qr.dto.assistance.AssistanceSuccessDTO;
import org.mzyyn.qr.entity.AssistanceRecordPO;
import org.mzyyn.qr.mapper.AssistanceRecordMapper;
import org.mzyyn.qr.service.AssistanceRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.mzyyn.qr.service.ShareService;
import org.mzyyn.qr.vo.user.ShareCodeVO;
import org.qr.xiaocao.common.enums.CommonResultEnum;
import org.qr.xiaocao.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 助力记录表 服务实现类
 * </p>
 *
 * @author lipeng
 * @since 2024-09-03
 */
@Service
public class AssistanceRecordServiceImpl extends ServiceImpl<AssistanceRecordMapper, AssistanceRecordPO> implements AssistanceRecordService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ShareService shareService;

    @Override
    public void assistanceSuccess(AssistanceSuccessDTO assistanceSuccessDTO){
        String assistanceCode = assistanceSuccessDTO.getCode();

        ShareCodeVO shareCodeVO = shareService.parseShareCode(assistanceCode);

        String beAssistedUserUuid =shareCodeVO.getUserUuid();
        //自己不允许助力
//        if( UserAuthContext.getUserInfo().getUuid().equals(beAssistedUserUuid) ){
//            throw new ServiceException(CommonResultEnum.COMMON_FAILED.getCode(),"自己不能为自己助力");
//        }

        //是否已经助力过了
        String assistanceKey = RedisKeyConstant.ASSISTANCE_RECORD + beAssistedUserUuid + ":" + UserAuthContext.getUserInfo().getUuid();
        String assistanceVal = stringRedisTemplate.opsForValue().get(assistanceKey);
        if(StrUtil.isNotEmpty(assistanceVal)){
//            throw new ServiceException(CommonResultEnum.COMMON_FAILED.getCode(),"30分钟只能为一个人助力一次");
        }

        AssistanceRecordPO assistanceRecordPO = new AssistanceRecordPO();
        assistanceRecordPO.setShareCode(shareCodeVO.getShareCode());
        assistanceRecordPO.setAssistanceName(UserAuthContext.getUserInfo().getUsername());
        assistanceRecordPO.setAssistanceUuid(UserAuthContext.getUserInfo().getUuid());
        assistanceRecordPO.setAssistanceImg(UserAuthContext.getUserInfo().getAvatar());
        assistanceRecordPO.setBeAssistedUuid(beAssistedUserUuid);
        assistanceRecordPO.setCreateTime(LocalDateTime.now());
        assistanceRecordPO.setUpdateTime(LocalDateTime.now());

        try {
            this.baseMapper.insert(assistanceRecordPO);
            stringRedisTemplate.opsForValue().set(
                    assistanceKey,
                    "1",
                    30, TimeUnit.MINUTES
            );

        }catch (Exception e){
            log.error("助力失败：{}",e);
            throw new ServiceException(CommonResultEnum.COMMON_FAILED.getCode(),"助力失败");
        }
    }

    @Override
    public void assistanceSuccessShishi(AssistanceSuccessDTO assistanceSuccessDTO) {

        this.assistanceSuccess(assistanceSuccessDTO);

        ShareCodeVO shareCodeVO = shareService.parseShareCode(assistanceSuccessDTO.getCode());

        shareService.receivePrizeShishi(assistanceSuccessDTO,shareCodeVO.getUserUuid(), ShareConstant.ASSISTANCE_INTEGRAL);
    }

    @Override
    public void huzhuSuccess(AssistanceSuccessDTO assistanceSuccessDTO) {
        String assistanceCode = assistanceSuccessDTO.getCode();

        ShareCodeVO shareCodeVO = shareService.parseShareCode(assistanceCode);

        String beAssistedUserUuid =shareCodeVO.getUserUuid();
        //自己不允许助力
//        if( UserAuthContext.getUserInfo().getUuid().equals(beAssistedUserUuid) ){
//            throw new ServiceException(CommonResultEnum.COMMON_FAILED.getCode(),"自己不能为自己助力");
//        }

        //是否已经助力过了
        String huzhuKey = RedisKeyConstant.HUZHU_RECORD + beAssistedUserUuid +"-"  + UserAuthContext.getUserInfo().getUuid();

        //助力的key  当前用户 只要存在说明当前用户已经互助过了
        if(Boolean.TRUE.equals(stringRedisTemplate.hasKey(huzhuKey))){
//            throw new ServiceException(CommonResultEnum.COMMON_FAILED.getCode(),"十分钟内只能助力一次，十分钟后再来助力吧！");
        }

        AssistanceRecordPO assistanceRecordPO = new AssistanceRecordPO();
        assistanceRecordPO.setShareCode(shareCodeVO.getShareCode());
        assistanceRecordPO.setAssistanceName(UserAuthContext.getUserInfo().getUsername());
        assistanceRecordPO.setAssistanceUuid(UserAuthContext.getUserInfo().getUuid());
        assistanceRecordPO.setAssistanceImg(UserAuthContext.getUserInfo().getAvatar());
        assistanceRecordPO.setBeAssistedUuid(beAssistedUserUuid);
        assistanceRecordPO.setCreateTime(LocalDateTime.now());
        assistanceRecordPO.setUpdateTime(LocalDateTime.now());

        try {
            this.baseMapper.insert(assistanceRecordPO);
            stringRedisTemplate.opsForValue().set(huzhuKey, UserAuthContext.getUserInfo().getUuid(),10L,TimeUnit.MINUTES);

            //本人+5 对方+10
            shareService.receivePrizeShishi(assistanceSuccessDTO, shareCodeVO.getUserUuid(), ShareConstant.HUZHU_INTEGRAL);
            shareService.receivePrizeShishi(assistanceSuccessDTO, UserAuthContext.getUserInfo().getUuid(), ShareConstant.HUZHU_INTEGRAL_SELF);
        }catch (Exception e){
            log.error("助力失败：{}",e);
            throw new ServiceException(CommonResultEnum.COMMON_FAILED.getCode(),"助力失败");
        }
    }

    @Override
    public Long assistancePeopleCount(String shareCode) {
        if( StrUtil.isEmpty(shareCode) ){
            return 0L;
        }

        LambdaQueryWrapper<AssistanceRecordPO> query = new LambdaQueryWrapper<>();
        query.eq(AssistanceRecordPO::getShareCode,shareCode);

        return this.baseMapper.selectCount(query);
    }

    @Override
    public List<AssistanceRecordPO> getAssistanceRecordList(String shareCode, Integer size) {
        if( StrUtil.isEmpty(shareCode) ){
            return new ArrayList<>();
        }

        if( null == size ){
            size = 10;
        }
        LambdaQueryWrapper<AssistanceRecordPO> query = new LambdaQueryWrapper<>();
        query.eq(AssistanceRecordPO::getShareCode,shareCode);
        query.orderByDesc(AssistanceRecordPO::getId);
        query.isNotNull(AssistanceRecordPO::getAssistanceImg);
        query.groupBy(AssistanceRecordPO::getAssistanceUuid);
        query.last("limit "+size);

        return this.baseMapper.selectList(query);
    }
}
